<?php

namespace app\proxyapi\controller;

use app\appapi\controller\BaseController;
use app\data\model\LiveAppList;
use app\data\model\LiveAppproxy;
use app\data\model\LiveProxyList;
use app\proxyapi\service\ProxyTokenService;

class Login extends BaseController
{
    //密码登录
    public function proxyPassLogin()
    {
        $post = $this->request->post();
        if(!isset( $post['user_account'], $post['user_password'], $post['app_info'])) $this->error('缺少参数！');
        if(!isset($post['app_info']['appName'])) $this->error('缺少参数！');
        if(!isset($post['app_info']['packageName'])) $this->error('缺少参数！');
        if(!isset($post['app_info']['versionName'])) $this->error('缺少参数！');
        if(!isset($post['app_info']['versionCode'])) $this->error('缺少参数！');

        //2.找到该用户ID
        $user = LiveProxyList::mk()->where(['user_account' => $post['user_account'],'deleted' => 0])->find();
        if (empty($user)) $this->error('不存在该账户！');
        if ($user['user_password'] != $post['user_password']) $this->error('密码不正确！');
        if ($user['user_state'] == 1) $this->error('当前用户禁止登录！');

        $proxyapp = LiveAppproxy::mk()->where(['id'=>1])->find();
        if($proxyapp['app_name'] != $post['app_info']['appName'] ||
            $proxyapp['app_package'] != $post['app_info']['packageName']
        ) $this->error('当前账户在该APP中不存在！');

        //生成token
        $tokenArr = ProxyTokenService::token($user['id']);
        if ($tokenArr[0] != 1) $this->error('token生成失败！');
        //更改用户
        LiveProxyList::mk()->where(['user_account' => $post['user_account']])->update([
            'login_num' => $user['login_num'] + 1,
            'login_ip' => $this->request->ip(),
            'login_time' => date('Y-m-d H:i:s'),
            'login_appName' => $post['app_info']['appName'],
            'login_packageName' => $post['app_info']['packageName'],
            'login_versionName' => $post['app_info']['versionName'],
            'login_versionCode' => $post['app_info']['versionCode'],
        ]);
        $app_name = LiveAppList::mk()->where(['app_id'=>$user['app_id']])->find()['app_name'];

        //直属类型 0不是直属 1直属
        $auto_dirtype = 0;
        //贴牌为直属
        if($user['user_autotype'] == 2 || in_array($user['pid'],[1,2])){
            $auto_dirtype = 1;
        }
        $this->success('登录成功！', [
            'token'         => $tokenArr[2]['token'],
            'uuid'          => $tokenArr[2]['uuid'],
            'time'          => $tokenArr[2]['time'],
            'nickname'      =>$user['user_nickname'],
            'app_id'        =>$user['app_id'],
            'app_name'      =>$app_name,
            'auto_type'     =>$user['user_autotype'],//授权类型 1代理 2贴牌
            'auto_dirtype'  =>$auto_dirtype,//直属类型 0不是直属 1直属
            'inte_yue'      =>$user['integral_balance'],//积分余额
        ]);
    }
}